<?php
namespace Home\Controller;

use Think\Controller;
use Base\FrontController;

class GetxinxiController extends Controller {

	function _initialize(){
	    $this->thirdAppid=C('third_app_id');
	    $this->thirdAppsecret=C('third_app_secret');
	    $this->appid=C('appid');
	    $this->scope = C('scope');
	    $this->sdk = new \Home\ORG\WeixinThirdSDK($this->thirdAppid,$this->thirdAppsecret);
	}

	//方太公众号网页授权

	public function fotile520(){
		//客户公众号的appid
		$appid = C('fotile_appid');
		//授权成功后的回跳地址
		$call_back_jump_url = C('fotile_webAuth_url');
		$this->huoqucode($appid,$call_back_jump_url);
	}

    //共用公众号网页授权方法
	private function huoqucode($client_appid,$call_back_jump_url){		
		try {
			$url = 'http://' . $_SERVER['HTTP_HOST'].'/Home/Getxinxi/call_back';
			if($_REQUEST["debug"]=='eosi'){
				$num = 'eosi';
			}
			else{
				//status 用s方法存储一个随机值  
				$num = rand(1,200);
			}
			//防止跨页提交设定一个随机值
			$_SESSION['csrf_ticket']=$num;
			//客户公众号的appid
			$appid = $client_appid;
			//授权成功后的回跳地址
			$_SESSION['call_back_jump_url'] = $call_back_jump_url;
			//网页授权scope
			$scope=$this->scope;
		    $jumpUrl = $this->sdk->shouquan($appid,$url,$scope,$num);
		    header('location:' . $jumpUrl);
		} catch (\Exception $e) {
			//$this->ajaxReturn('', $e->getMessage(), '400');
			$this->mydump('huoqucode Exception:');
			$this->mydump($e);
		}
	} 

	public function call_back(){		
		try {
			$state = $_REQUEST["state"];
			$status = $_SESSION['csrf_ticket'];
			if($status && ($status != $state) ){
				throw new \Exception($state."status参数错误,请刷新页面重试".$status, -1);
			}
			$code = $_REQUEST['code'];
			$appid = $_REQUEST['appid'];
			if(isset($code) && isset($appid)){
				$datas = array();
				$res = $this->sdk->getAccessToken($code,$appid);	
				$this->mydump('getAccessToken RESULT:');	
				$this->mydump($res);			
				//用access_token获取用户基本信息
				$opopenid=$res['openid'];
				
				//判断授权作用域为snsapi_userinfo，如果是，则获取用户信息，否只能获取oppid
				if($res['scope'] == 'snsapi_base'){
					$datas['openid'] = $opopenid;
				}else{
					//todo 处理用户信息新增到表
					$userInfo = $this->sdk->thirdUserInfo($appid,$opopenid,$res['access_token']);
					$datas=$userInfo;
				}
				//$this->ajaxReturn($datas,'1',1);
				$datas['appid']=$appid ;
				$this->userAdd($datas);
				// echo('hello '.$datas['nickname'].",你已成功网页授权");
				$jumpUrl=$_SESSION['call_back_jump_url'].'?callBackStatus=1';
				echo('<script>window.location="'.$jumpUrl.'"</script>');
		
			}else{
				throw new \Exception("你禁止了网页授权，请允许.", -2);
			}
		} catch (\Exception $e) {
			//$this->ajaxReturn('', $e->getMessage(), '400');
			$this->mydump('exception:');
			$this->mydump($e);
		}
	}

	private function mydump($msg){
		if($_REQUEST['state']=='eosi'){
			dump($msg);
		}
	}
	function tiaoshi(){
		//$m=D('Home/AuthorizationInfo');
		//$api_authorizer_token=$m->getAuthorizerAccessToken(C('appid'));
		$this ->display();
	}

	//4	wx66c97d1778ea9bd3	p6yMg7sCz4McChNxu_0bz-HCiWkAQBsRuq-N9R-C83EYNFShLmKmEvBjpWg3lKs2IRbQJPLMdZHWs1AatrgqG-iiqtov7tvqMuIaH3yIpv9Ym8KkfjiRH2J16jZ5KQnLMANgAGDRFS	7200	refreshtoken@@@YHV9Sg9Fu54gbSqYm1x7peZHXR6zh73kAumEg6dD518	[{"funcscope_category":{"id":4}}]	1493782139	0	1493788139	1
	//沁园H5 授权后测试自定义分享的页面
	function qinyuan(){
		//$m=D('Home/AuthorizationInfo');
		//$api_authorizer_token=$m->getAuthorizerAccessToken(C('appid'));
		$this ->display();
	}


	//模板消息
	private function mobanxiaoxi($appid){
		$m=D('Home/AuthorizationInfo');
        $api_authorizer_token=$m->getAuthorizerAccessToken($appid);
        $datas = array('touser'=>'o2_qyjjZJXeGwZ6Uf9OKfWztS9U8',

        	'template_id'=>'ZjTwE2ugN1LVh0wRPidjbjuxMA01Hv3zL7YyPxPxsYk',
        	'url'=>'http://weixin.qq.com/download',
        	'data'=>array(
        			'first'=>array(
        					'value'=>"您的安防设备正在发出报警！",
        					'color'=>'#173177'
        				),
        			'keyword1'=>array(
        					'value'=>"罗盼",
        					'color'=>'#173177'
        				),
        			'keyword2'=>array(
        					'value'=>"河南大华安防科技股份有限公司",
        					'color'=>'#173177'
        				),
        			'keyword3'=>array(
        					'value'=>"2017年3月2日 14:11:25",
        					'color'=>'#173177'
        				),
        			'remark'=>array(
        					'value'=>"此为测试模板消息，不必理会",
        					'color'=>'#173177'
        				),
        		)
        	);
        $result = $this->sdk->moban($appid,json_encode($datas),$api_authorizer_token);
        dump($result);
	}

	/**
	 * 记录用户信息到表里
	 */

	public function userAdd($info) {
		$openid=$info['openid'];
		
		$model=M('weixin_user');
		$result=$model->where(array('openid'=>$openid))->find();
		$data=array();
		$data['appid'] = $info['appid'];
		$data['nickname']=array_key_exists('nickname', $info)?$info['nickname']:'';
		$data['sex']=array_key_exists('sex', $info)?$info['sex']:-99;
		$data['province']=array_key_exists('province', $info)?$info['province']:'';
		$data['city']=array_key_exists('city', $info)?$info['city']:'';
		$data['country']=array_key_exists('country', $info)?$info['country']:'';
		$data['headimgurl']=array_key_exists('headimgurl', $info)?$info['headimgurl']:'';
		if($result){
			$data['update_time']=time();
			$res=$model->where(array('openid'=>$openid))->save($data);
			$data=array_merge($result,$data);
		}else{
			$data['openid']=$openid;
			$data['create_time']=time();
			$data['status'] = 1;
			$res=$model->add($data);
			$data['id'] = $res;
		}
		if($res === false){
			$this->error('网络原因记录您的信息失败,请稍候再试.',$this->illegal_url);
		}
		else {
			// $data['appid'] = C('fotile_appid');
			
			$this->changeSession(C('weixin_session_key'), $data);
			// dump($_SESSION);
		}
		return $data;
	}
	private function changeSession($key, $value) {
		$_SESSION[$key] = $value;
		session($key,$value);
	}
}